package com.ruoyi.system.api.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OkHttpUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.InterfaceOperationLog;
import com.ruoyi.system.api.domain.StEquipmentAccessory;
import com.ruoyi.system.api.service.IInterfaceOperationLogService;
import okhttp3.FormBody;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.mapper.StMajorPartMapper;
import com.ruoyi.system.api.domain.StMajorPart;
import com.ruoyi.system.api.service.IStMajorPartService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.util.ObjectUtils;

/**
 * 主要设备信息 主要设备信息Service业务层处理
 *
 * @author ruoyi
 * @date 2020-03-09
 */
@Service
public class StMajorPartServiceImpl implements IStMajorPartService {

    private static final Logger log = LoggerFactory.getLogger(StEquipmentAccessoryServiceImpl.class);

    @Autowired
    private StMajorPartMapper stMajorPartMapper;

    /**
     * 接口调用日志
     */
    @Autowired
    private IInterfaceOperationLogService iInterfaceOperationLogService;

    /**
     * 配置文件
     */
    @Autowired
    private Global global;


    /**
     * 查询主要设备信息 主要设备信息
     *
     * @param id 主要设备信息 主要设备信息ID
     * @return 主要设备信息 主要设备信息
     */
    @Override
    public StMajorPart selectStMajorPartById(Long id) {
        return stMajorPartMapper.selectStMajorPartById(id);
    }

    /**
     * 查询主要设备信息 主要设备信息列表
     *
     * @param stMajorPart 主要设备信息 主要设备信息
     * @return 主要设备信息 主要设备信息
     */
    @Override
    public List<StMajorPart> selectStMajorPartList(StMajorPart stMajorPart) {
        return stMajorPartMapper.selectStMajorPartList(stMajorPart);
    }

    /**
     * 新增主要设备信息 主要设备信息
     *
     * @param stMajorPart 主要设备信息 主要设备信息
     * @return 结果
     */
    @Override
    public int insertStMajorPart(StMajorPart stMajorPart) {
        stMajorPart.setCreateTime(DateUtils.getNowDate());
        return stMajorPartMapper.insertStMajorPart(stMajorPart);
    }

    /**
     * 修改主要设备信息 主要设备信息
     *
     * @param stMajorPart 主要设备信息 主要设备信息
     * @return 结果
     */
    @Override
    public int updateStMajorPart(StMajorPart stMajorPart) {
        stMajorPart.setUpdateTime(DateUtils.getNowDate());
        return stMajorPartMapper.updateStMajorPart(stMajorPart);
    }

    /**
     * 删除主要设备信息 主要设备信息对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStMajorPartByIds(String ids) {
        return stMajorPartMapper.deleteStMajorPartByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除主要设备信息 主要设备信息信息
     *
     * @param id 主要设备信息 主要设备信息ID
     * @return 结果
     */
    @Override
    public int deleteStMajorPartById(Long id) {
        return stMajorPartMapper.deleteStMajorPartById(id);
    }

    /**
     * 添加主要备件信息
     *
     * @param majorPart
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 3:10 下午
     */
    @Override
    public ResponseWithData<?> addMajorPart(StMajorPart majorPart) {

        /** 调用CC端接口 */
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("addInstrumentPart.asmx/addInstrumentPartHandle");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        /** POST请求 参数赋值 */
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("InstrumentCode", majorPart.getInstrumentNo());
        builder.add("Engineer_id", majorPart.getEnginnerId().toString());
        builder.add("Parts_Code", majorPart.getPartNumber());
        builder.add("Parts_Name", StringUtils.isEmpty(majorPart.getPartName()) ? "" : majorPart.getPartName());
        builder.add("Parts_Serial", majorPart.getSerialNumber());
        if (ObjectUtils.isEmpty(majorPart.getWarrantyEndTime())) {
            builder.add("Parts_WarrantyEnd", "");
        } else {
            builder.add("Parts_WarrantyEnd", majorPart.getWarrantyEndTime());
        }
        if (ObjectUtils.isEmpty(majorPart.getWarrantyStartTime())) {
            builder.add("Parts_WarrantyStart", "");
        } else {
            builder.add("Parts_WarrantyStart", majorPart.getWarrantyStartTime());
        }
        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.59新增主要备件接口");
        interfaceOperationLog.setInterfaceType("addMajorPart");
        interfaceOperationLog.setServiceNo(majorPart.getServiceNo());
        interfaceOperationLog.setFseId(majorPart.getEnginnerId().toString());
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setInterfaceRequest(JSONObject.toJSONString(majorPart));
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数：" + interfaceResponseBody;
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            if (res.code() == 200) {
                interfaceState = "1";
            } else {
                interfaceState = "2";
            }
        } catch (Exception e) {
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if ("0".equals(interfaceState)) {
            return new ResponseWithData().success().msg("查询失败 调用CC端获取TL名下工程师接口发生异常").code(202);
        }
        if (res != null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {

                    JSONArray jsonArr = obj.getJSONArray("record");
                    return new ResponseWithData<>().success().msg("添加成功").code(200);

                }
            }
        }
        return new ResponseWithData<>().success().msg("添加失败").code(201);
    }

    /**
     * 查看主要备件列表
     *
     * @param serviceNo
     * @param instrumentNo
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 3:13 下午
     */
    @Override
    public ResponseWithData<?> selectMajorParts(String instrumentNo, String enginnerId, String serviceNo) {
        /** 调用CC端接口 */
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("getInstrumentPart.asmx/getInstrumentPartHandle");
        /** POST请求 参数赋值 */
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("InstrumentCode", instrumentNo);
        builder.add("Engineer_id", enginnerId);

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.58获取主要备件接口");
        interfaceOperationLog.setInterfaceType("selectMajorParts");
        interfaceOperationLog.setServiceNo(serviceNo);
        interfaceOperationLog.setFseId(enginnerId);
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setInterfaceRequest("instrumentNo=" + instrumentNo + ",enginnerId=" + enginnerId + ",serviceNo=" + serviceNo);
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数：" + interfaceResponseBody;
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            if (res.code() == 200) {
                interfaceState = "1";
            } else {
                interfaceState = "2";
            }
        } catch (Exception e) {
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if ("0".equals(interfaceState)) {
            return new ResponseWithData().success().msg("查询失败 调用CC端获取TL名下工程师接口发生异常").code(202);
        }
        if (res != null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {

                    JSONArray jsonArr = obj.getJSONArray("record");
                    return new ResponseWithData<>().success(jsonArr).msg("查询成功").code(200);

                }
            }
        }
        return new ResponseWithData<>().success().msg("查询失败").code(201);
//        List<StMajorPart> datas = stMajorPartMapper.selectMajorPartsByServiceNoAndHelpId(serviceNo, helpId);
//        if (null == datas) {
//            datas = new ArrayList<>();
//        }
//        return new ResponseWithData<>().success(datas).code(200);
    }

    /**
     * 移除主要备件信息
     *
     * @param partsId
     * @param enginnerId
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 3:17 下午
     */
    @Override
    public ResponseWithData<?> removeMajorPart(String instrumentNo, String enginnerId, String partsId, String serviceNo) {

        /** 调用CC端接口 */
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("delInstrumentPart.asmx/delInstrumentPartHandle");
        /** POST请求 参数赋值 */
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("InstrumentCode", instrumentNo);
        builder.add("Engineer_id", enginnerId);
        builder.add("Parts_ID", partsId);

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.60删除主要备件接口");
        interfaceOperationLog.setInterfaceType("removeMajorPart");
        interfaceOperationLog.setServiceNo(serviceNo);
        interfaceOperationLog.setFseId(enginnerId);
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setInterfaceRequest("instrumentNo=" + instrumentNo + ",enginnerId=" + enginnerId + ",serviceNo=" + serviceNo + ",partsId=" + partsId);
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数：" + interfaceResponseBody;
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            if (res.code() == 200) {
                interfaceState = "1";
            } else {
                interfaceState = "2";
            }
        } catch (Exception e) {
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if ("0".equals(interfaceState)) {
            return new ResponseWithData().success().msg("查询失败 调用CC端获取TL名下工程师接口发生异常").code(202);
        }
        if (res != null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {

                    JSONArray jsonArr = obj.getJSONArray("record");
                    return new ResponseWithData<>().success(jsonArr).msg("删除成功").code(200);

                }
            }
        }
        return new ResponseWithData<>().success().msg("删除失败").code(201);

//        StMajorPart stMajorPart = stMajorPartMapper.selectStMajorPartById(id);
//        if (null != stMajorPart) {
//            stMajorPart.setDelFlag("2");
//            stMajorPart.setUpdateBy(enginnerId.toString());
//            stMajorPart.setUpdateTime(new Date());
//            stMajorPartMapper.updateStMajorPart(stMajorPart);
//            return new ResponseWithData<>().success().msg("移除主要备件信息成功").code(200);
//        }
//        return new ResponseWithData<>().error().msg("移除主要备件信息失败, 主要备件信息不存在");
    }
}
